package com.example.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author heshao
 * @date 2021/1/14 11:58
 */
@Slf4j
@Component
@Primary
public class MultiSwaggerResourcesProvider implements SwaggerResourcesProvider {

    private final String SWAGGER_SUFFIX = "/v3/api-docs";
    private final GatewayProperties gatewayProperties;

    public MultiSwaggerResourcesProvider(GatewayProperties gatewayProperties) {
        this.gatewayProperties = gatewayProperties;
    }

    @Override
    public List<SwaggerResource> get() {

        List<SwaggerResource> resources = new ArrayList<>();
        gatewayProperties.getRoutes()
                .forEach(routeDefinition -> {
                    routeDefinition.getPredicates()
                            .stream()
                            .filter(predicateDefinition -> "Path".equals(predicateDefinition.getName()))
                            .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs().get("_genkey_0").replace("/**", SWAGGER_SUFFIX))));
                });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name : [{}], location : [{}]", name, location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("3.0");
        return swaggerResource;
    }
}
